﻿#region

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web.Mvc;
using Tateeda.ClinicalStudy.Base.Modules.Common.Enumeration;
using Tateeda.ClinicalStudy.Base.Modules.Common.Extenstions;
using Tateeda.ClinicalStudy.Base.Modules.Infrastructure.Interfaces.Services;
using Tateeda.ClinicalStudy.Base.Modules.Models.Medication;
using Tateeda.ClinicalStudy.Base.Modules.Models.Study;
using Tateeda.ClinicalStudy.Base.Modules.Models.StudyForm;
using Tateeda.ClinicalStudy.Base.Modules.Models.User;
using Tateeda.ClinicalStudy.Base.Web.Common;

#endregion

#region - Legal -

///<legal>
/// Copyright © 2011, Tateeda Media Network
/// All rights reserved. http://tateeda.com
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions
/// are met:
///
/// - Redistributions of source code must retain the above copyright
/// notice, this list of conditions and the following disclaimer.
///
/// - Neither the name of the Tateeda Media Network, nor the names of its
/// contributors may be used to endorse or promote products
/// derived from this software without specific prior written
/// permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
/// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
/// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
/// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
/// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
/// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING,
/// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
/// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
/// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
/// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
/// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/// POSSIBILITY OF SUCH DAMAGE.
///</legal>

#endregion - Legal -

namespace Tateeda.ClinicalStudy.Base.Web.Controllers {

    public class StudyController : Controller {
        //
        // GET: /Study/
        private readonly IStudyService _service;

        public StudyController(IStudyService service) {
            _service = service;
        }

        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public ActionResult Index() {
            var appointments = MyAppointmentsSearch(DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1), false);
            return View(appointments);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public ActionResult MyAppointments(DateTime from, DateTime to, bool? showForAll) {
            var appointments = MyAppointmentsSearch(from, to, showForAll);
            return View(appointments);
        }

        /// <summary>
        ///   Starts the specified appointment for subject.
        /// </summary>
        /// <param name = "sid">The subject id.</param>
        /// <param name = "apid">The appointment id.</param>
        /// <returns></returns>
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public ActionResult Visit(int sid, int apid) {
            var appointment = _service.GetAppointment(apid);
            var reqForms = new Dictionary<string, ICollection<StudyFormModel>>();
            var inProgForms = new Dictionary<string, ICollection<StudyFormModel>>();
            var completeForms = new Dictionary<string, ICollection<StudyFormModel>>();
            var visitName = appointment.Visit.Name;
            var inprForms = _service.GetAppointmentForms(appointment.AppointmentId, (int)StudyStatus.InProgressStatus);
            inProgForms.Add(visitName, inprForms);

            var compForms = _service.GetAppointmentForms(appointment.AppointmentId, (int)StudyStatus.CompletedStatus);
            completeForms.Add(visitName, compForms);

            var allForms = _service.GetAppointmentForms(appointment.AppointmentId, null);
            var reqFormsList = new Collection<StudyFormModel>();
            //Filter out filled forms
            foreach (var reqFrm in allForms) {
                if (inprForms.Where(f => f.FormId == reqFrm.FormId).SingleOrDefault() == null &&
                    compForms.Where(f => f.FormId == reqFrm.FormId).SingleOrDefault() == null) {
                    reqFormsList.Add(reqFrm);
                }
            }

            reqForms.Add(visitName, reqFormsList);

            ViewBag.ReqFormsDictionary = reqForms;
            ViewBag.InProgressFormsDictionary = inProgForms;
            ViewBag.CompletedFormsDictionary = completeForms;
            //List of all substances per this visit
            ViewBag.AllSubstances = _service.GetSubjectSubstancesPerAppointment(sid, appointment.AppointmentId);
            ViewBag.VistName = visitName;
            ViewBag.AppointmentId = apid;
            ViewBag.SubjectId = sid;
            ViewBag.IsFirstVisit = _service.GetFirstVisit().Name == visitName;

            ViewBag.MinNumOfDays = 7; //TODO: [SK] Read this from DB settings table.
            ViewBag.CanSubmitForm = true; //TODO: [SK] Need to calculate this value
            return View(appointment);
        }

        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public JsonResult GetPrescriptionDrugCategory() {
            var list = _service.GetDrugCategories();
            var cats = new Collection<DrugCategoryModel>();
            foreach (var c in list) {
                var dcm = new DrugCategoryModel { Name = c.Name, DrugCategoryId = c.DrugCategoryId, Code = c.Code };
                cats.Add(dcm);
            }
            return Json(cats);
        }

        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public JsonResult GetPrescriptionDrugClass(int categoryId) {
            var list = _service.GetDrugClasses(categoryId);
            var classes = new Collection<DrugClassModel>();
            foreach (var c in list) {
                var dcm = new DrugClassModel { Name = c.Name, DrugCategoryId = c.DrugCategoryId, DrugClassId = c.DrugClassId };
                classes.Add(dcm);
            }
            return Json(classes);
        }

        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public JsonResult GetPrescriptionDrugNames(int classId) {
            var list = _service.GetDrugsByClass(classId);
            var drugs = new Collection<DrugModel>();
            foreach (var d in list) {
                var dm = new DrugModel {
                    Name = d.Name,
                    DrugClassId = d.DrugClassId,
                    DrugId = d.DrugId,
                    DrugTypeId = d.DrugTypeId
                };
                drugs.Add(dm);
            }
            return Json(drugs);
        }

        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public JsonResult AddMedicationHistory(int subjectId, int appointmentId, int categoryId, int classId,
                                               int drugNameId, string dose,
                                               string doseUnit, DateTime startDate, DateTime? endDate,
                                               bool isBeforeStudy,
                                               int multipleTrialId, int durationUsedWeeks, int reasonStoppedId,
                                               int responseTypeId, int treatmentInducedId, string comments) {
            const int weeklyFrequency = 18; //FROM CODE Table ID 18.
            var sDrug = new SubjectDrugModel {
                AppointmentId = appointmentId,
                Comments = comments,
                CreatedOn = DateTime.UtcNow,
                Dosage = dose,
                DosageFrequencyId = weeklyFrequency,
                DrugId = drugNameId,
                DurationUsed = durationUsedWeeks,
                EndDate = endDate,
                IsBeforeStudy = true,
                IsChanged = false,
                IsCurrent = endDate.HasValue == false,
                IsStopped = endDate.HasValue,
                MultipleTrialsId = multipleTrialId,
                ReasonStoppedId = reasonStoppedId,
                ReasonTypeId = responseTypeId,
                StartDate = startDate,
                Status = StudyStatus.ActiveStatus.ToStatusInt(),
                SubjectId = subjectId,
                TreatmentInducedId = treatmentInducedId,
                UpdatedOn = DateTime.UtcNow
            };

            var drugs = _service.AddSubjectMedicationHistory(sDrug);

            return Json(drugs);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public JsonResult AddSubstance(int subjectId, int appointmentId, string kind, string name, int dose, string unit,
                                       string comment, int frequencyId) {
            var curAppUser = _service.GetAppUserByLoginName(User.Identity.Name);
            var substance = new RecreationalDrugOrSubstanceModel {
                SubjectId = subjectId,
                AppointementId = appointmentId,
                Comments = comment,
                Unit = unit,
                Dose = dose.ToString(),
                Frequency = frequencyId,
                Name = name,
                Status = StudyStatus.ActiveStatus.ToStatusInt(),
                Createdby = curAppUser.UserName,
                CreatedOn = DateTime.UtcNow,
                TypeName = kind
            };

            var list = _service.AddSubstance(substance);
            return Json(list);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public void DeleteSubjectsSubstance(int substanceId) {
            _service.DeleteSubstance(substanceId);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public JsonResult FindDrugName(string name) {
            var list = _service.FindNonPsychoDrugsByName(name);
            return Json(list);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public JsonResult AddSubjectNonSychotropicDrug(int subjectId, int appointmentId, int classId, string drugNameId,
                                                       int dose,
                                                       string doseUnit, DateTime startDate, DateTime? endDate,
                                                       bool isBeforeStudy, string comments, int frequencyId) {
            int drugId;
            var drug = _service.FindDrugByName(drugNameId);

            if (drug == null) {
                const int oct = 2;
                var dm = new DrugModel {
                    DrugClassId = classId,
                    DrugTypeId = oct,
                    Name = drugNameId,
                    CreatedOn = DateTime.UtcNow,
                    Description = "Over counter Non psychotropic drug",
                    Status = 0
                };
                drugId = _service.AddNewDrug(dm);
            } else {
                drugId = drug.DrugId;
            }

            var sDrug = new SubjectDrugModel {
                AppointmentId = appointmentId,
                SubjectId = subjectId,
                Comments = comments,
                DrugId = drugId,
                Dosage = dose.ToString(),
                DosageType = doseUnit,
                StartDate = startDate,
                EndDate = endDate,
                IsBeforeStudy = false,
                IsCurrent = endDate.HasValue == false,
                IsStopped = endDate.HasValue,
                UpdatedOn = DateTime.UtcNow,
                CreatedOn = DateTime.UtcNow,
                Status = StudyStatus.ActiveStatus.ToStatusInt(),
                DosageFrequencyId = frequencyId
            };
            var list = _service.AddSubjectDrug(sDrug);
            return Json(list);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public JsonResult AddPrescriptionDrug(int subjectId, int appointmentId, int classId, int drugNameId, int dose,
                                              string doseUnit, DateTime startDate, DateTime? endDate, bool isBeforeStudy,
                                              string comments, int frequencyId) {
            var sDrug = new SubjectDrugModel {
                AppointmentId = appointmentId,
                SubjectId = subjectId,
                Comments = comments,
                DrugId = drugNameId,
                Dosage = dose.ToString(),
                DosageType = doseUnit,
                StartDate = startDate,
                EndDate = endDate,
                IsBeforeStudy = false,
                IsCurrent = endDate.HasValue == false,
                IsStopped = endDate.HasValue,
                UpdatedOn = DateTime.UtcNow,
                CreatedOn = DateTime.UtcNow,
                Status = StudyStatus.ActiveStatus.ToStatusInt(),
                DosageFrequencyId = frequencyId
            };
            var list = _service.AddSubjectDrug(sDrug);
            return Json(list);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public void DeleteSubjectsPrescriptionDrug(int subjectDrugId) {
            _service.DeleteSubjectDrug(subjectDrugId);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public JsonResult StopPrescriptionDrug(int subjectDrugId, DateTime stopDate) {
            return Json(_service.StopPrescriptionDrug(subjectDrugId, stopDate));
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdminAppuser)]
        public JsonResult ChangePrescriptionDrugDose(int subjectDrugId, int dose, DateTime changeDate) {
            var sDrug = _service.GetSubjectsDrug(subjectDrugId);
            sDrug.Dosage = dose.ToString();
            sDrug.IsChanged = true;
            sDrug.UpdatedOn = changeDate.ToUniversalTime();
            var drugs = _service.EditSubjectsDrug(sDrug);
            return Json(drugs);
        }

        #region - Private Functions

        private ICollection<AppointmentModel> MyAppointmentsSearch(DateTime from, DateTime to, bool? showForAll) {
            var appUser = _service.GetAppUserByName(User.Identity.Name);

            if (appUser == null) return null;

            var showAll = showForAll.HasValue;
            var toDate = new DateTime(to.Year, to.Month, to.Day, DateTime.Now.AddHours(8).Hour, DateTime.Now.Minute, 0);
            var appointments = _service.FindAppointmentsForDates(
                                            from.ToUniversalTime(),
                                            toDate.ToUniversalTime(),
                                            appUser.SiteId, appUser.AppUserId,
                                            showAll);

            foreach (var appt in appointments) {
                var isInProgress =
                    appt.AppointmentForms.Where(af => af.Status == StudyStatus.InProgressStatus.ToStatusInt()).Count() >
                    0;
                if (isInProgress) {
                    appt.Status = StudyStatus.InProgressStatus.ToStatusInt();
                }
            }

            //TODO: [SK] FIX THIS

            #region Can Submit/view Form

            const bool canSubmitData = false;
            ViewData["minNumOfDays"] = 7;

            //if (canSubmitValue.Equals("yes") || canSubmitValue.Equals("true")) {
            //    int minNumOfDays = appService.GetSetting((int)Constants.SettingsType.FromEntryMinDays).Value.ToSafeInt();
            //    ViewData["minNumOfDays"] = minNumOfDays;
            //    canSubmitData = true;
            //}
            ViewData["CanSubmitForm"] = canSubmitData;

            #endregion Can Submit/view Form

            return appointments;
        }

        #endregion
    }
}